//
//  PublicQRCodeViewController.m
//  AAIM
//
//  Created by 远的小布丁 on 2020/1/22.
//  Copyright © 2020 AAIM. All rights reserved.
//

#import "PublicQRCodeViewController.h"

@interface PublicQRCodeViewController ()
@property (nonatomic,strong)UIView * backView;
@property (nonatomic,strong)UIView * bottomBackView;
@property (nonatomic,strong)UIImageView * headImg;
@property (nonatomic,strong)UIImageView * QRCodeImg;
@property (nonatomic,strong) UILabel * nameLbl;
@property (nonatomic,strong) UILabel * introLbl;
@property (nonatomic,strong) UILabel * tipLabel;
@property (nonatomic,strong) UIButton * saveBtn;
@property (nonatomic,strong)PublicModel * model;
@end

@implementation PublicQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = KHEXCOLOR(@"#F4F4F4");
    [self.view addSubview:self.bottomBackView];
    [self.bottomBackView addSubview:self.backView];
    [self.bottomBackView addSubview:self.headImg];
    [self.backView addSubview:self.nameLbl];
    [self.backView addSubview:self.introLbl];
    [self.backView addSubview:self.QRCodeImg];
    [self.backView addSubview:self.tipLabel];
    [self.bottomBackView addSubview:self.saveBtn];
    [self setUIMosory];
    [self getQRCodeData];
}

- (void)getQRCodeData{
    KWeakSelf;
    [MBProgressHUD showMessage:@"加载中,请稍等！" toView:self.view];
    [RequestData PostPublicQRCodeWithToken:[LoginManager shareLoginManager].userModel.token userUUid:[LoginManager shareLoginManager].userModel.uuid withPublicUDID:_udid Success:^(NSDictionary * _Nonnull Dict) {
        NSLog(@"二维码：%@",Dict);
        weakSelf.model = [PublicModel mj_objectWithKeyValues:Dict[@"data"]];
        [weakSelf.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,weakSelf.model.head]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            weakSelf.headImg.image = image;
        }];
        weakSelf.nameLbl.text = weakSelf.model.title;
        weakSelf.introLbl.text = weakSelf.model.describe;
        [weakSelf.QRCodeImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userInfoImage,weakSelf.model.qrcode]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            weakSelf.QRCodeImg.image = image;
        }];
        [MBProgressHUD hideHUDForView:self.view];
    } failure:^(NSString * _Nonnull errMsg) {
        [MBProgressHUD hideHUDForView:self.view];
        [weakSelf showTipHudWithText:errMsg];
    }];
}

- (void)setUIMosory{
    [_bottomBackView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.equalTo(self.gk_navigationBar.mas_bottom);
              make.left.equalTo(self.view.mas_left);
              make.right.equalTo(self.view.mas_right);
              make.height.offset(570.f);
    }];
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.gk_navigationBar.mas_bottom).offset(32.f);
        make.left.equalTo(self.view.mas_left).offset(29.f);
        make.right.equalTo(self.view.mas_right).offset(-29.f);
        make.height.offset(450.f);
    }];
    [_headImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backView.mas_top).offset(-22.f);
        make.centerX.equalTo(self.backView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(70.f, 70.f));
    }];
    [_nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headImg.mas_bottom).offset(15.f);
         make.centerX.equalTo(self.backView.mas_centerX);
        make.height.offset(25.f);
    }];
    [_introLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameLbl.mas_bottom).offset(7);
         make.centerX.equalTo(self.backView.mas_centerX);
        make.height.offset(21.f);
    }];
    
    [_QRCodeImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.introLbl.mas_bottom).offset(8);
        make.centerX.equalTo(self.backView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(229.f, 229.f));
    }];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.QRCodeImg.mas_bottom).offset(8);
        make.centerX.equalTo(self.backView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth-30, 17.f));
    }];
    
    [_saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backView.mas_bottom).offset(25);
        make.centerX.equalTo(self.backView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(120.f, 60.f));
    }];
    [_QRCodeImg setContentScaleFactor:[[UIScreen mainScreen] scale]];
    _QRCodeImg.contentMode =  UIViewContentModeScaleAspectFit;
    
}

#pragma mark 生成image
- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"2--%@",image);
    return image;
    
}


//保存
- (void)saveClick:(UIButton *)sender{
    NSLog(@"保存");
    UIImage * image = [self makeImageWithView:self.bottomBackView withSize:CGSizeMake(kScreenWidth, kScreenHeight-self.gk_navigationBar.bottom)];
     [MBProgressHUD showMessage:@"保存中..." toView:self.view];
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
    {
        [MBProgressHUD hideHUDForView:self.view];
        NSString *message = @"成功";
        if (!error) {
            message = @"成功保存到相册";
            [MBProgressHUD showSuccess:message afterDelay:3];
        }else
        {
            message = [error description];
            [MBProgressHUD showError:@"保存失败" afterDelay:3];
        }
    
}

- (UIButton *)saveBtn{
    if (!_saveBtn) {
        _saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_saveBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_saveBtn setImage:[UIImage imageNamed:@"保存按钮"] forState:UIControlStateNormal];
        [_saveBtn setTitleEdgeInsets:UIEdgeInsetsMake(15, -18, -15, 18)];
        [_saveBtn setImageEdgeInsets:UIEdgeInsetsMake(-15, 15, 15, -15)];
        [_saveBtn addTarget:self action:@selector(saveClick:) forControlEvents:UIControlEventTouchUpInside];
        [_saveBtn setTitleColor:KHEXCOLOR(@"#AFAFAF") forState:UIControlStateNormal];
        _saveBtn.titleLabel.font = kMainFont(15);
    }
    return _saveBtn;
}

- (UILabel *)introLbl{
   if (!_introLbl) {
        _introLbl = [[UILabel alloc]init];
        _introLbl.font = kFont(15);
        _introLbl.textColor = KHEXCOLOR(@"#AFAFAF");
        _introLbl.text = @"";
    }
    return _introLbl;
}

- (UILabel *)tipLabel{
   if (!_tipLabel) {
        _tipLabel = [[UILabel alloc]init];
        _tipLabel.font = kFont(12);
       _tipLabel.textAlignment = 1;
        _tipLabel.textColor = KHEXCOLOR(@"#262B2F");
        _tipLabel.text = @"扫一扫，关注公众号";
    }
    return _tipLabel;
}

-(UILabel *)nameLbl{
    if (!_nameLbl) {
        _nameLbl = [[UILabel alloc]init];
        _nameLbl.font = kFont(18);
        _nameLbl.textColor = KHEXCOLOR(@"#262B2F");
        _nameLbl.text = @"";
    }
    return _nameLbl;
}

-(UIImageView *)QRCodeImg{
    if (!_QRCodeImg) {
        _QRCodeImg = [[UIImageView alloc]init];
        _QRCodeImg.image = [UIImage imageNamed:@""];
    }
    return _QRCodeImg;
}

-(UIImageView *)headImg {
    if (!_headImg) {
        _headImg = [[UIImageView alloc]init];
        _headImg.layer.cornerRadius = 35.f;
        _headImg.layer.masksToBounds = YES;
        _headImg.image = [UIImage imageNamed:@""];
    }
    return _headImg;
}

-(UIView *)backView{
    if (!_backView) {
        _backView = [UIView new];
        _backView.layer.cornerRadius = 5;
        _backView.layer.masksToBounds = YES;
        _backView.backgroundColor = [UIColor whiteColor];
    }
    return _backView;
}

-(UIView *)bottomBackView{
    if (!_bottomBackView) {
        _bottomBackView = [UIView new];
        _bottomBackView.backgroundColor = [UIColor clearColor];
    }
    return _bottomBackView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
